// B站首页添加热点按钮
const VideoInfoDetail = 'video-info-detail-list video-info-detail-content'; // 播放页面页面速度放入的class盒子名称

export function BilibiliPublicCallBack() {
  // 点击标题 复制到剪贴板
  document.addEventListener('click', (event) => {
    if (event.target.className.includes('video-title')) {
      let curAddress = location.href.split('/?spm_id_from')[0] || '';
      let curTitle = event.target.innerText;
      copyToClipboard(curAddress + ' ' + curTitle);
      CopySuccessTips();
    }
  });

  if (document.querySelector('#viewbox_report')) {
    // 视频播放页面(标题所在的div的ID)
    window.Bilibili_Video_speed = 1.75; // 设置网页初始化的播放速度
    // window.Bilibili_Video_src = '';
    // window.Bilibili_Video_Timer = null;
    // if (window.Bilibili_Video_Timer) {
    //   window.Bilibili_Video_Timer = null;
    // } else {
    //   window.Bilibili_Video_Timer = setInterval(() => {
    //     let videoSrc = document.getElementsByTagName('video')[0]?.src;
    //     if (videoSrc !== window.Bilibili_Video_src) {
    //       let currentVideoEl = document.getElementsByTagName('video')[0];
    //       currentVideoEl.playbackRate = window.Bilibili_Video_speed; // 读取上次播放的速度
    //     } else {
    //       window.Bilibili_Video_src = videoSrc;
    //     }
    //   }, 1000);
    // }

    setTimeout(() => {
      BilibiliVideoPageCallBack();
    }, 2000);
  } else {
    // 首页
  }
}
function insertFirst(parent, newChild) {
  parent.insertBefore(newChild, parent.firstChild);
}

// B站视频播放页面的回调函数
function BilibiliVideoPageCallBack() {
  // if (!document.querySelector('#viewbox_report')) return;
  const containerSelector = '.' + VideoInfoDetail.split(' ').join('.');

  function addButtonsOnce() {
    if (window.boxueBiliInit) return;
    window.boxueBiliInit = true;
    try {
      let styleElement = document.createElement('style');
      styleElement.innerHTML = `
        .honor.item.honor-rank{display:none!important}
        .dm.item{display:none!important}
        .copyright.item{display:none!important}
      `;
      document.head.appendChild(styleElement);
    } catch (e) {
      console.error('append style failed', e);
    }

    try {
      // 尽量确保播放与默认倍速项存在
      const video = document.getElementsByTagName('video')[0];
      if (video && video.paused) {
        document
          .getElementsByClassName('bpx-player-ctrl-btn-icon')?.[0]
          ?.click?.();
      }

      // 触发默认播放速度菜单项，兼容不同顺序
      const rateItems = document.getElementsByClassName(
        'bpx-player-ctrl-playbackrate-menu-item'
      );
      if (rateItems && rateItems.length > 0) {
        // 尝试点击第一个可用项（多数页面第一个为默认）
        rateItems[0].click();
      }

      // 关闭弹幕（如果已经是开的）
      const danmakuSwitch = document.querySelector(
        '.bilibili-player-video-danmaku-switch .bui-switch-input'
      );
      if (danmakuSwitch?.checked) {
        danmakuSwitch.click();
      }
    } catch (e) {
      console.warn('player basic setup failed', e);
    }

    // 添加自定义按钮（复用已有函数）
    try {
      [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0].forEach((v) =>
        setDoubleSpeed(v)
      );
      [-10, 10, 20, 30].forEach((s) => SetFastForward(s));
      SetZoomIn();
      Set1080();
    } catch (e) {
      console.error('add custom buttons failed', e);
    }
  }

  // 备用轮询（最多尝试 20 次，每 500ms）
  let attempts = 0;
  const fallbackTimer = setInterval(() => {
    const btns = document.querySelectorAll('.boxue_bilibili_speedbutton');
    if (!btns.length) {
      addButtonsOnce();
      clearInterval(fallbackTimer);
    } else {
      attempts++;
      if (attempts > 20) {
        clearInterval(fallbackTimer);
        console.warn('未能在限定时间内找到目标容器：', containerSelector);
      }
    }
  }, 500);

  let count_2 = 0;
  let timer_2 = setInterval(() => {
    if (count_2 > 10) {
      clearInterval(timer_2);
      return;
    }
    let videoSrc = document.getElementsByTagName('video')[0]?.src;
    if (videoSrc !== window.Bilibili_Video_src) {
      let currentVideoEl = document.getElementsByTagName('video')[0];
      currentVideoEl.playbackRate = window.Bilibili_Video_speed; // 读取上次播放的速度
    } else {
      window.Bilibili_Video_src = videoSrc;
    }
    count_2++;
  }, 500);
}

// 设置放大
function SetZoomIn() {
  var spanEl = document.createElement('span');
  spanEl.innerHTML = '放大';
  spanEl.className = 'boxue_bilibili_speedbutton';
  spanEl.onclick = () => {
    const videoElement = document.getElementsByTagName('video')[0];
    if (videoElement) {
      const dataScale = videoElement.getAttribute('data-scale');
      if (dataScale === '1.88') {
        videoElement.style.transform = 'scale(1)';
        videoElement.style.position = 'relative';
        videoElement.style.top = '0';
        videoElement.setAttribute('data-scale', '1');
      } else {
        videoElement.style.transform = 'scale(1.88)';
        videoElement.style.position = 'relative';
        videoElement.style.top = '-34px';
        videoElement.setAttribute('data-scale', '1.88');
      }
    }
  };
  document.getElementsByClassName(VideoInfoDetail)[0].appendChild(spanEl);
}
// 设置1080P
function Set1080() {
  var spanEl = document.createElement('span');
  spanEl.innerHTML = '1080';
  spanEl.className = 'boxue_bilibili_speedbutton';
  spanEl.onclick = () => {
    let textEls = document.getElementsByClassName(
      'bpx-player-ctrl-quality-text'
    );
    let flag = false;
    for (let i = 0; i < textEls.length; i++) {
      if (textEls[i].innerText === '1080P 高清') {
        textEls[i].parentNode.click();
        flag = true;
      }
    }
    flag ? CopySuccessTips('设置成功') : CopySuccessTips('设置失败');
  };
  document.getElementsByClassName(VideoInfoDetail)[0].appendChild(spanEl);
}

// 设置快进
function SetFastForward(val = 10) {
  var spanEl = document.createElement('span');
  spanEl.innerHTML = val + 's';
  spanEl.className = 'boxue_bilibili_speedbutton';
  spanEl.onclick = () => speedOfProgress(val);
  document.getElementsByClassName(VideoInfoDetail)[0].appendChild(spanEl);
}
// 调整进度(秒)
function speedOfProgress(val = 10) {
  let currentVideoEl = document.getElementsByTagName('video')[0];
  if (currentVideoEl) {
    currentVideoEl.currentTime += val;
  }
}

function setDoubleSpeed(val) {
  var spanEl = document.createElement('span');
  // spanEl.innerHTML = val + '倍';
  spanEl.innerHTML = val;
  spanEl.className = 'boxue_bilibili_speedbutton';
  spanEl.onclick = () => BilibiliSetSpeed(val);
  document.getElementsByClassName(VideoInfoDetail)[0].appendChild(spanEl);
}

// 设置播放速度
function BilibiliSetSpeed(val = 2) {
  window.Bilibili_Video_speed = val;
  let selectElement = document.getElementsByClassName(
    'bpx-player-ctrl-playbackrate-menu-item'
  )[3];
  selectElement.innerHTML = val + 'x';
  selectElement.setAttribute('data-value', val);
  selectElement.click();

  console.log('%c设置播放速度为' + val + '倍', 'color:red;font-size:20px;');
  if (document.getElementsByTagName('video')[0].paused) {
    document.getElementsByClassName('bpx-player-ctrl-btn-icon')?.[0]?.click?.(); // 开始播放
  }
}

function CustomDateFtt(date, fmt) {
  if (date != null && date != '' && date != undefined) {
    if (typeof date == 'string') {
      if (date.includes('T')) {
        date = new Date(date);
      } else {
        date = date.replace(/-/g, '/');
      }
    }
    var date = new Date(date);
    var o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds(), //毫秒
    };
    o.S < 100 && (o.S = o.S < 10 ? '00' + o.S : '0' + o.S);
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      );
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        );
  } else {
    fmt = '';
  }
  return fmt;
}
